package com.example.jixeishi1.service;



import com.example.jixeishi1.dao.CartMapper;
import com.example.jixeishi1.dao.ProductMapper;
import com.example.jixeishi1.entity.CartEntity;
import com.example.jixeishi1.entity.ProductEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 
 *
 * @author cola
 * @date 2021-11-15 22:12:57
 */
@Service
public class CartService {
    @Resource
    CartMapper cartMapper;
    @Resource
    ProductMapper productMapper;

    public List<CartEntity> getShopping() {
        List<CartEntity> shoppingEntities  = cartMapper.getShoppingInfo();
        return shoppingEntities;
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveShopping(Integer id) {
        ProductEntity productEntity = productMapper.getCommodityById(id);
        CartEntity cartEntity = new CartEntity();
        cartEntity.setInTime(new Date());
        cartEntity.setNum(1);
        cartEntity.setCmmodityName(productEntity.getCommodityName());
        cartEntity.setPricecommodity(productEntity.getPrice());
        cartEntity.setCommodityId(id);
        cartEntity.setSubtitle(productEntity.getCommodityType());
        cartEntity.setMainImage(productEntity.getMainImage());
        CartEntity cartEntity2 = cartMapper.getShoppingInfoByComid(id);
        if(ObjectUtils.isEmpty(cartEntity2)){
            cartMapper.saveShopping(cartEntity);
        }else{
            cartEntity.setNum(cartEntity2.getNum() + 1);
            cartEntity.setId(cartEntity2.getId());
            cartMapper.updateShoppingById22(cartEntity);

        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addShopping(Integer id,Integer num) {
        CartEntity cartEntity = new CartEntity();
            cartEntity.setNum(num + 1);
            cartEntity.setId(id);
            cartMapper.updateShoppingById22(cartEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void hyphen(Integer id,Integer num) {
        CartEntity cartEntity = new CartEntity();
        if(num > 1){
            num = num - 1;
        }else{

        }
        cartEntity.setNum(num);
        cartEntity.setId(id);
        cartMapper.updateShoppingById22(cartEntity);
    }

    public void updateShoppingById(List<CartEntity> shopping) {
        cartMapper.updateShoppingById(shopping);
    }

    public void deleteShopping(Integer id) {
        cartMapper.deleteShopping(id);
    }

    public void deleteShoppingAll() {
        cartMapper.deleteShoppingAll();
    }

}

